package com.nidu.demo.file.storage.impl;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.nidu.demo.common.enums.FileStorageTypeEnum;
import com.nidu.demo.file.storage.FileStorage;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Component;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.Map;

/**
 * 本地文件存储实现
 *
 * @author auto
 */
@Slf4j
@Component
public class LocalFileStorage implements FileStorage {

    @Override
    public String upload(MultipartFile file, String path, Map<String, Object> config) {
        try {
            // 获取配置参数
            String basePath = (String) config.get("basePath");
            String domain = (String) config.get("domain");
            
            if (StrUtil.isEmpty(basePath)) {
                basePath = System.getProperty("user.dir") + "/upload";
            }
            
            // 确保目录存在
            File uploadDir = new File(basePath);
            if (!uploadDir.exists()) {
                uploadDir.mkdirs();
            }
            
            // 生成文件名
            String originalFilename = file.getOriginalFilename();
            String extension = FileUtil.extName(originalFilename);
            String fileName = IdUtil.fastSimpleUUID() + "." + extension;
            
            // 构建完整路径
            String fullPath = basePath + "/" + path + "/" + fileName;
            File targetFile = new File(fullPath);
            
            // 确保父目录存在
            File parentDir = targetFile.getParentFile();
            if (!parentDir.exists()) {
                parentDir.mkdirs();
            }
            
            // 保存文件
            file.transferTo(targetFile);
            
            // 返回相对路径
            return path + "/" + fileName;
            
        } catch (IOException e) {
            log.error("本地文件上传失败", e);
            throw new RuntimeException("文件上传失败", e);
        }
    }

    @Override
    public void delete(String path, Map<String, Object> config) {
        String basePath = (String) config.get("basePath");
        if (StrUtil.isEmpty(basePath)) {
            basePath = System.getProperty("user.dir") + "/upload";
        }
        
        String fullPath = basePath + "/" + path;
        File file = new File(fullPath);
        if (file.exists()) {
            file.delete();
        }
    }

    @Override
    public String getUrl(String path, Map<String, Object> config) {
        String domain = (String) config.get("domain");
        if (StrUtil.isEmpty(domain)) {
            domain = "http://localhost:8080";
        }
        
        return domain + "/file/" + path;
    }

    @Override
    public Integer getStorageType() {
        return FileStorageTypeEnum.LOCAL.getType();
    }
}
